package com.ijiuchuang.jc_localization.model.settings;

import com.ijiuchuang.jc_localization.app.Config;
import com.ijiuchuang.jc_localization.bean.bmob.AppVersion;
import com.ijiuchuang.jc_localization.bean.lite.Setts;
import com.ijiuchuang.jc_localization.contract.settings.SettingsContract;
import com.ijiuchuang.jc_localization.network.ApiModel;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.ArrayList;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Veev on 2016/6/17
 *
 * @link 384506557@qq.com
 */
public class SettingsModel implements SettingsContract.Model {

    private LiteOrm liteOrm = Config.liteOrm;

    @Override
    public void checkVersion(Subscriber<AppVersion> subscriber) {
        ApiModel.bmobGetApi()
                .getVersionName(Config.AppVersionObj)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    @Override
    public void save(String key, int value) {
        Setts setts = new Setts(key, value);
        //setts.setValueInt(value);
        // 这里若用 update， 第一项数据无法保存
        liteOrm.save(setts);
    }

    @Override
    public int loadInteger(String key) {
        QueryBuilder<Setts> equals = new QueryBuilder<>(Setts.class)
                .whereEquals(Setts.COL_KEY, key);
        ArrayList<Setts> list = liteOrm.query(equals);
        if (!list.isEmpty()) {
            return list.get(0).getValueInt();
        }
        return 0;
    }

    @Override
    public boolean loadBoolean(String key) {
        QueryBuilder<Setts> equals = new QueryBuilder<>(Setts.class)
                .whereEquals(Setts.COL_KEY, key);
        if (liteOrm.query(equals) != null) {
            ArrayList<Setts> list = liteOrm.query(equals);
            if (list.size() != 0) {
                return list.get(0).getValueBool();
            }
        }
        return false;
    }
}
